package com.whr.utils;

import com.whr.bean.User;
import com.whr.service.RoleService;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyInterceptor implements HandlerInterceptor {
    @Resource
    private RoleService roleService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        if (uri.indexOf("/user/login") >= 0 || uri.indexOf("/user/index") >= 0 || uri.indexOf("/user/main") >= 0) {
            return true;
        }
        User user = (User) httpServletRequest.getSession().getAttribute("user");
        if (user == null) {
            httpServletResponse.sendRedirect("/user/index/welcome");
            return false;
        }
        String role = user.getRole();
        String path = roleService.getPathByRole(role);
        String[] paths = path.split("[,;]");
        for (String p : paths) {
            if (uri.indexOf(p) >= 0) {
                return true;
            }
        }
        httpServletResponse.sendRedirect("/user/error");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
